<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 1.文件分片
    function sliceFile(file, chunkSize) {
      const fileSize = file.size;
      const totalChunks = Math.ceil(fileSize / chunkSize);
      const chunks = [];

      for (let i = 0; i < totalChunks; i++) {
        const start = i * chunkSize;
        const end = Math.min(start + chunkSize, fileSize);
        const chunk = file.slice(start, end);
        chunks.push(chunk);
      }

      return chunks;
    }
    // 2.上传文件
    function uploadChunk(url, data, onProgress) {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();

        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/octet-stream');
        xhr.onload = () => resolve(xhr);
        xhr.onerror = reject;
        xhr.upload.onprogress = onProgress;

        xhr.send(data);
      });
    }
    // 处理异常情况
    function retryChunk(url, data, onProgress, retryCount) {
      return new Promise((resolve, reject) => {
        function doRequest() {
          uploadChunk(url, data, onProgress)
            .then(resolve)
            .catch(error => {
              if (retryCount === 0) {
                reject(error);
              } else {
                setTimeout(doRequest, 1000);
                retryCount--;
              }
            });
        }

        doRequest();
      });
    }
    // 暂停上传和恢复上传
    function pauseUpload() {
      isPaused = true;
    }

    function resumeUpload() {
      isPaused = false;
      uploadChunks(chunks.slice(completedChunks));
    }

    function uploadChunks(chunks) {
      if (isPaused) {
        return;
      }

      const chunk = chunks[completedChunks];
      const url = '/upload';

      const onProgress = event => {
        const progress = (completedChunks / totalChunks) * 100 + (event.loaded / event.total) * (1 / totalChunks) * 100;
        updateProgressBar(progress);
      };

      retryChunk(url, chunk, onProgress, 3)
        .then(() => {
          completedChunks++;

          if (completedChunks < totalChunks) {
            uploadChunks(chunks);
          } else {
            // Upload completed
          }
        })
        .catch(error => {
          // Handle error
        });
    }

    const chunks = sliceFile(file, chunkSize);
    let totalChunks = chunks.length;
    let completedChunks = 0;
    let isPaused = false;

    uploadChunks(chunks);

  </script>
</body>

</html>